package com.howen.framework;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.WaitForSelectorState;
import com.microsoft.playwright.options.WaitUntilState;

public class BasePage {
    protected Page page;
    protected String baseUrl;

    //有参数构造方法
    public BasePage(Page page, String baseUrl) {
        this.page = page;
        this.baseUrl = baseUrl;
        initBrowserSettings();
    }
    //初始化浏览器设置
    protected void initBrowserSettings() {
        // 设置全局超时
        page.setDefaultTimeout(30000);
        // 最大化浏览器窗口
        page.setViewportSize(1920, 1080);
    }

    /**
     * 拼接url
     * @param path
     */
    public void navigate(String path) {
        String url = baseUrl + (path.startsWith("/") ? path : "/" + path);
        page.navigate(url, new Page.NavigateOptions()
                .setWaitUntil(WaitUntilState.NETWORKIDLE));
    }

    /**
     * 等待元素出现点击
     * @param selector
     */
    public void click(String selector) {
        page.locator(selector).click();
    }

    /**
     * 输入内容
     * @param selector
     * @param value
     */
    public void fill(String selector, String value) {
        page.locator(selector).fill(value);
    }

    /**
     * 定位器
     * @param selector
     * @return
     */
    public Locator locator(String selector) {
        return page.locator(selector);
    }

    /**
     * 截图
     * @return
     */
    public byte[] takeScreenshot() {
        return page.screenshot(new Page.ScreenshotOptions()
                .setFullPage(true));
    }

    /**
     * 获取元素文本信息
     * @param text
     * @return
     */
    public Locator getByText(String text) {
        return page.getByText(text);
    }

    /**
     * 文本定位
     * @param placeholder
     * @return
     */
    public Locator getByPlaceholder(String placeholder) {
        return page.getByPlaceholder(placeholder);
    }

    /**
     * 处理iframe
     */
    public FrameLocator frameLocator(String selector) {
        return page.frameLocator(selector);
    }

    /**
     * 等待元素操作
     * @param selector
     * @param timeout
     */
    public void clickWithWait(String selector, int timeout) {
        page.locator(selector).click(new Locator.ClickOptions().setTimeout(timeout));
    }

    public void close() {
        if (page != null) {
            page.close();
        }
    }
}
